#include "musiclist.h"
#include<QMimeDatabase>
#include<QSqlQuery>
#include<QSqlError>

MusicList::MusicList() {}

void MusicList::addMusicByUrl(const QList<QUrl> &urls)
{
    for(const auto& url : urls){
        //检查音乐文件是否已经添加过
        QString musicPath = url.toLocalFile();
        if(_musicPaths.contains(musicPath))
            continue;

        //分析文件类型，如果是音乐类型那么就通过url构建music对象，保存到musicList中
        QMimeDatabase mimedata;
        QMimeType mime = mimedata.mimeTypeForFile(url.toLocalFile());
        if(mime.name() != "audio/mpeg" && mime.name() != "audio/mflac" && mime.name() != "audio/mp3")
        {
            continue;
        }

        //如果歌曲还没有被加载过，同时是一个有效的歌曲文件，加载进歌曲列表中
        _musicPaths.insert(musicPath);

        // 如果是⾳乐⽂件，加⼊歌曲列表
        _musicList.push_back(url);
    }

}

iterator MusicList::begin()
{
    return _musicList.begin();
}

iterator MusicList::end()
{
    return _musicList.end();
}

iterator MusicList::findMusicById(const QString &musicId)
{
    iterator it = _musicList.begin();
    while(it != _musicList.end()){
        if(it->getMusicId() == musicId){
            break;
        }
        ++it;
    }
    return it;
}

//让数据库中写入数据
void MusicList::writeToDB()
{
    for(const auto& music : _musicList){
        QString musicId = music.getMusicId();
        QSqlQuery query;

        query.prepare("select exists(select 1 from musicInfo where musicId = ?)");
        query.addBindValue(musicId);
        if(!query.exec()){
            qDebug()<<"查询失败: "<<query.lastError().text();
            return;
        }
        if(query.next()){
            bool isExists = query.value(0).toBool();
            if(isExists)
            {
                // musicId的歌曲已经存在
                // 2. 存在：不需要再插⼊musci对象，此时只需要将isLike和isHistory属性进⾏更新
                query.prepare("UPDATE musicInfo SET isLike = ?, isHistory = ? WHERE musicId = ?");
                query.addBindValue(music.getIsLike()? 1 : 0);
                query.addBindValue(music.getIsHistory()? 1 : 0);
                query.addBindValue(musicId);
                if(!query.exec())
                {
                    qDebug()<<"更新失败: "<<query.lastError().text();
                }
                qDebug()<<"更新music信息: "<<music.getMusicName()<<" "<<musicId;
            }
            else
            {
                // 3. 不存在：直接将music的属性信息插⼊数据库
                query.prepare("INSERT INTO musicInfo(musicId, musicName,musicSinger, albumName, musicUrl,\
                duration, isLike, isHistory)VALUES(?,?,?,?,?,?,?,?)");
                query.addBindValue(musicId);
                query.addBindValue(music.getMusicName());
                query.addBindValue(music.getSingerName());
                query.addBindValue(music.getAlbumName());
                query.addBindValue(music.getMusicUrl().toLocalFile());
                query.addBindValue(music.getDuration());
                query.addBindValue(music.getIsLike() ? 1 : 0);
                query.addBindValue(music.getIsHistory()? 1 : 0);

                if(!query.exec())
                {
                    qDebug()<<"插⼊失败: "<<query.lastError().text();
                    return;
                }
                qDebug()<<"插⼊music信息: "<<music.getMusicName()<<" "<<musicId;
            }

    }
    }
}
//从数据库中读取数据
void MusicList::readFromDB()
{
    QString sql("SELECT musicId, musicName, musicSinger, albumName,\
    duration, musicUrl, isLike, isHistory FROM musicInfo");
    QSqlQuery query;
    if(!query.exec(sql))
    {
        qDebug()<<"数据库查询失败";
        return;
    }
    qDebug() << "查询完成";
    while(query.next())
    {
        //qDebug() << query.value(0).toString();
        Music music;
        music.setMusicId(query.value(0).toString());
        music.setMusicName(query.value(1).toString());
        music.setSingerName(query.value(2).toString());
        music.setAlbumName(query.value(3).toString());
        music.setDuration(query.value(4).toLongLong());
        music.setMusicUrl("file:///" + query.value(5).toString());
        music.setIsLike(query.value(6).toBool());
        music.setIsHistory(query.value(7).toBool());
        _musicList.push_back(music);

        _musicPaths.insert(music.getMusicUrl().toLocalFile());

    }
    // for(auto& url : _musicPaths){
    //     qDebug() << url;
    // }
}
